package com.ukefu.webim.web.handler.api.v2;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ukefu.core.UKDataContext;
import com.ukefu.util.Menu;
import com.ukefu.util.UKTools;
import com.ukefu.webim.service.cache.CacheHelper;
import com.ukefu.webim.service.repository.ExtentionRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.service.repository.UserRoleRepository;
import com.ukefu.webim.util.RestResult;
import com.ukefu.webim.util.RestResultType;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.handler.api.request.RequestValues;
import com.ukefu.webim.web.model.Extention;
import com.ukefu.webim.web.model.User;
import com.ukefu.webim.web.model.UserRole;



@RestController
@RequestMapping("/v2/tokens")
public class V2LoginController extends Handler{

	@Autowired
	private UserRepository userRepository;
	
	@Autowired
	private ExtentionRepository extentionRepository;
	
	@Value("${uk.im.server.port}")  
    private Integer port;
	
	@Autowired
	private UserRoleRepository userRoleRes ;

	@RequestMapping(method = RequestMethod.POST)
    @Menu(type = "apps" , subtype = "token" , access = true)
        public ResponseEntity<RestResult> login(HttpServletRequest request , @RequestBody RequestValues<User> values) {
    	User loginUser = null ;
    	ResponseEntity<RestResult> entity = new ResponseEntity<>(null, HttpStatus.UNAUTHORIZED) ;
    	
    	/**
    	 * 检验session锁定时间
    	 */
		
    	
    	if(values!=null && values.getData()!=null && !StringUtils.isBlank(values.getData().getUsername()) && !StringUtils.isBlank(values.getData().getPassword())) {
    		loginUser = userRepository.findByUsernameAndPasswordAndDatastatus(values.getData().getUsername() , UKTools.md5(values.getData().getPassword()),false) ;
	        if(loginUser!=null && !StringUtils.isBlank(loginUser.getId())){
	        	loginUser.setLogin(true);
	        	List<UserRole> userRoleList = userRoleRes.findByOrgiAndUser(loginUser.getOrgi(), loginUser);
	        	if(userRoleList!=null && userRoleList.size()>0){
	        		for(UserRole userRole : userRoleList){
	        			loginUser.getRoleList().add(userRole.getRole()) ;
	        		}
	        	}
	        	Extention extention = null ;
	        	if(!StringUtils.isBlank(loginUser.getExtid())) {
	        		extention = extentionRepository.findById(loginUser.getExtid()) ;
	        	}
	        	loginUser.setLastlogintime(new Date());
	        	if(!StringUtils.isBlank(loginUser.getId())){
	        		userRepository.save(loginUser) ;
	        	}
	        	String auth = UKTools.getUUID();
	        	CacheHelper.getApiUserCacheBean().put(auth, loginUser, UKDataContext.SYSTEM_ORGI);
	        	loginUser.setPassword(null);
	        	entity = new ResponseEntity<>(new RestResult(RestResultType.OK , auth ,loginUser ,extention), HttpStatus.OK) ;
	        }else{
	        	entity = new ResponseEntity<>(new RestResult(RestResultType.OK , null , null ,null), HttpStatus.OK) ;
	        }
    	}else{
    		entity = new ResponseEntity<>(new RestResult(RestResultType.OK , null , null ,null), HttpStatus.OK) ;
        }
        return entity;
    }
    
    @SuppressWarnings("rawtypes")
	@RequestMapping(method = RequestMethod.DELETE)
    public ResponseEntity logout(HttpServletRequest request , @RequestHeader(value="authorization") String authorization) {
    	CacheHelper.getApiUserCacheBean().delete(authorization, UKDataContext.SYSTEM_ORGI);
        return new ResponseEntity<>(HttpStatus.OK);
    }
    
    @RequestMapping(value = "/check")
	@Menu(type = "apps" , subtype = "batch" , access = true)
	    public ResponseEntity<RestResult> batchDelete(HttpServletRequest request , @RequestHeader(value="authorization") String authorization) throws Exception {
		final RestResult restResult = new RestResult(RestResultType.OK);
    	if(org.apache.commons.lang3.StringUtils.isNotBlank(authorization)){
    		if(CacheHelper.getApiUserCacheBean().getCacheObject(authorization, UKDataContext.SYSTEM_ORGI) != null){
    			restResult.setStatus(RestResultType.OK);
    		}else{
    			//token失效
    			restResult.setStatus(RestResultType.AUTH_ERROR);
    		}
    	}else{
    		restResult.setMsg("authorization");
    		restResult.setStatus(RestResultType.NO_PASS_MUST_ENTER);
    	}
    	
		return new ResponseEntity<>(restResult,HttpStatus.OK);
    }

}